from django.http import HttpResponse, JsonResponse
from rest_framework import status
from rest_framework.decorators import api_view
from rest_framework.response import Response
from .serializers import DstdomainSerializer, SrcipSerializer
from .models import Srcip, Dstdomain
import json

from .squid_api_v2 import *


# Create your views here.
def index(request):
    return HttpResponse(u"你好!这里是京东五星电器基础架构部门访问之地，闲人误入！")


# 插入IP白名单到数据库
@api_view(['GET', 'POST'])
def insertsrcip(request):
    # 获取前端提交的信息
    json_data = request.body.decode("utf-8")
    # 将json字符串转换为python中的dict
    python_data = json.loads(json_data)
    # print(python_data)
    hosts_list = python_data["hosts"].split(",")
    description = python_data["description"]
    for host in hosts_list:
        data = dict({"hosts": host,
                     "description": description}
                    )
        print(data)
        # 反序列化
        serailzer = SrcipSerializer(data=data)
        # 校验前端数据
        try:
            serailzer.is_valid(raise_exception=True)
        except Exception as e:
            return JsonResponse(serailzer.errors)
        # 校验成功之后的数据, 可以使用validated_data属性来获取
        # 插入数据库
        Srcip.objects.create(**serailzer.validated_data)
    return HttpResponse(u"IP白名单插入成功！")


# 获取数据库所有合法源IP
@api_view(['GET', 'POST'])
def getsrciplist(request):
    if request.method == 'GET':
        srcip = Srcip.objects.all()
        serializer = SrcipSerializer(srcip, many=True)
        return Response(serializer.data)

    elif request.method == 'POST':
        serializer = SrcipSerializer(data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)


# 插入域名白名单
@api_view(['GET', 'POST'])
def insertdomain(request):
    # 获取前端提交的信息
    json_data = request.body.decode("utf-8")
    # 将json字符串转换为python中的dict
    python_data = json.loads(json_data)
    # print(python_data)
    domain_list = python_data["dstdomain"].split(",")
    for domain in domain_list:
        data = dict({"dstdomain": domain})
        # 反序列化
        serailzer = DstdomainSerializer(data=data)
        # 校验前端数据
        try:
            serailzer.is_valid(raise_exception=True)
        except Exception as e:
            return JsonResponse(serailzer.errors)
        # 校验成功之后的数据, 可以使用validated_data属性来获取
        # 插入数据库
        project = Dstdomain.objects.create(**serailzer.validated_data)
        # 序列化输出
        DstdomainSerializer(instance=project)
    return HttpResponse(u"域名白名单插入成功！")


# 获取数据库所有域名白名单
@api_view(['GET', 'POST'])
def getdstdomainlist(request):
    if request.method == 'GET':
        dstdomain = Dstdomain.objects.all()
        serializer = DstdomainSerializer(dstdomain, many=True)
        return Response(serializer.data)

    elif request.method == 'POST':
        serializer = DstdomainSerializer(data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)


# 从数据库获取所有合法IP并重新写入到squid配置中
@api_view(['GET', 'POST'])
def fluship(request):
    if request.method == 'GET':
        srcip = Srcip.objects.all()
        serializer = SrcipSerializer(srcip, many=True)
        python_datas = serializer.data
        print("正在更改配置请稍后。。。")
        for python_data in python_datas:
            # print(python_data['hosts'], python_data[next(reversed(python_data))])
            hosts = python_data['hosts']
            description = python_data[next(reversed(python_data))]
            # print(hosts, description)
            # 将数据库中配置刷入squid服务器
            addip(hosts, description)
        # return Response(serializer.data)
        print("配置已生效！！！")
        return Response(status=status.HTTP_201_CREATED)

    elif request.method == 'POST':
        serializer = SrcipSerializer(data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
